package cn.bitkit.component.id;

import cn.bitkit.base.exception.BusinessAssert;
import cn.bitkit.component.context.SpringContext;
import cn.bitkit.component.redis.BasicRedisKey;
import org.springframework.data.redis.core.StringRedisTemplate;

public class RedisId {

    public static final long SEGMENT_SIZE = 1000;
    private static volatile long segmentId = 0;
    private static volatile long sequence = 0;

    private static synchronized long getId(){
        if(sequence >= SEGMENT_SIZE || segmentId == 0){
            StringRedisTemplate stringRedisTemplate = SpringContext.getAssertedBean(StringRedisTemplate.class);
            BusinessAssert.isNotNull(stringRedisTemplate, "获取机器id失败:redis not found");
            stringRedisTemplate.opsForValue().setIfAbsent(BasicRedisKey.BASIC_REDIS_ID, "100000");
            Long id = stringRedisTemplate.opsForValue().increment(BasicRedisKey.BASIC_REDIS_ID);
            BusinessAssert.isNotNull(id, "redis 操作异常");
            segmentId = id;
            sequence = 0;
        }
        sequence++;
        return segmentId * SEGMENT_SIZE + sequence;
    }
}
